import json
from typing import Dict, Any, List

from biz.cmd.func.mysql import MySQLReviewFunc


class MySQLReviewTool:
    """MySQL数据库表结构审查工具"""
    
    def __init__(self):
        self.mysql_func = None
    
    def _get_mysql_func(self):
        """延迟初始化MySQLReviewFunc"""
        if self.mysql_func is None:
            self.mysql_func = MySQLReviewFunc()
        return self.mysql_func
    
    def get_name(self) -> str:
        return "mysql_review"
    
    def get_description(self) -> str:
        return "MySQL数据库表结构设计审查和性能优化建议"
    
    def get_input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "host": {
                    "type": "string",
                    "description": "数据库主机地址",
                    "default": "localhost"
                },
                "port": {
                    "type": "integer",
                    "description": "数据库端口",
                    "default": 3306
                },
                "user": {
                    "type": "string",
                    "description": "数据库用户名",
                    "default": "root"
                },
                "password": {
                    "type": "string",
                    "description": "数据库密码"
                },
                "database": {
                    "type": "string",
                    "description": "数据库名称"
                },
                "pattern": {
                    "type": "string",
                    "description": "表名通配符 (支持LIKE语法，如 user%、log_%)，留空表示全部表",
                    "default": ""
                }
            },
            "required": ["password", "database"]
        }
    
    def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
        try:
            # 获取参数
            host = arguments.get("host", "localhost")
            port = arguments.get("port", 3306)
            user = arguments.get("user", "root")
            password = arguments["password"]
            database = arguments["database"]
            pattern = arguments.get("pattern", "")
            
            # 设置MySQL连接参数
            mysql_func = self._get_mysql_func()
            mysql_func.host = host
            mysql_func.port = port
            mysql_func.user = user
            mysql_func.password = password
            mysql_func.database = database
            mysql_func.pattern = pattern if pattern else None
            
            # 获取数据库表结构
            schema = mysql_func.get_mysql_schema()
            
            if not schema["tables"]:
                return {
                    "success": False,
                    "error": "未匹配到任何表，请检查通配符或数据库是否正确"
                }
            
            # 转换为JSON格式
            schema_text = json.dumps(schema, indent=4, ensure_ascii=False)
            
            # 进行AI审查
            review_result = mysql_func.review_and_strip_code(schema_text)
            
            return {
                "success": True,
                "schema": schema,
                "review_result": review_result,
                "tables_count": len(schema["tables"]),
                "database_info": {
                    "host": host,
                    "port": port,
                    "database": database,
                    "pattern": pattern or "全部表"
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"MySQL审查失败: {str(e)}"
            }